package com.example.lijianwen.startproject_401ljw.model;

import com.example.lijianwen.startproject_401ljw.service.weatherService;
import com.example.lijianwen.startproject_401ljw.bean.WeatherResult;
import com.example.lijianwen.startproject_401ljw.iface.WeatherIface;
import com.example.lijianwen.startproject_401ljw.iface.WeatherListener;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by lijianwen on 2017/3/14.
 */

public class WeatherModel implements WeatherIface{

    //网络数据获取框架
    private Retrofit retrofit;

    private String BASEURL = "http://www.weather.com.cn/";


    public WeatherModel() {
        //Retrofit实例化 3-1
        retrofit = new Retrofit.Builder().baseUrl(BASEURL).addConverterFactory(GsonConverterFactory.create()).build();
    }

    public void getWeather(String cityno, final WeatherListener listener){
        weatherService WeatherService = retrofit.create(weatherService.class);
        Call<WeatherResult> call = WeatherService.getResult(cityno);
        //Retrofit接口使用3-3
        call.enqueue(new Callback<WeatherResult>() {
            @Override
            public void onResponse(Call<WeatherResult> call, Response<WeatherResult> response) {
                if(response.isSuccessful() && response.body()!=null)
                    listener.onResonse(response.body().getWeatherInfo());
                else
                    listener.onFail("onResponse error");
            }

            @Override
            public void onFailure(Call<WeatherResult> call, Throwable t) {
                listener.onFail(t.toString());
            }
        });
    }
}
